package com.cs.bd.mopub.mopubstate;

import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.location.Location;
import android.os.PowerManager;
import android.view.ViewGroup;
import android.widget.FrameLayout;

import com.cs.bd.mopub.fragment.ActivityListener;
import com.cs.bd.mopub.utils.NullListener;
import com.cs.bd.utils.DrawUtils;
import com.cs.bd.utils.LogUtils;
import com.mopub.mobileads.MoPubErrorCode;
import com.mopub.mobileads.MoPubView;

public class CsMopubView
        extends FrameLayout
        implements MoPubView.BannerAdListener, ActivityListener {
    public static int sDpW = 300;
    public static int sDpH = 250;
    public static int sDpW_320 = 320;
    public static int sDpH_50 = 50;
    private boolean mIsDestroy;

    public void onActivityResume() {
        this.mIsBackground = false;
        if (!this.mIsDestroy) {
            this.mMopubState.onActivityResume();
        }
    }

    public void onActivityDestroy() {
    }

    public void onActivityPause() {
        this.mIsBackground = true;
        if (!this.mIsDestroy) {
            this.mMopubState.onActivityPause();
        }
    }

    public String getAppMonetId() {
        return this.AppMonetId;
    }

    public void setAppMonetId(String appMonetId) {
        this.AppMonetId = appMonetId;
    }

    public static enum AutoFreshType {
        NORMOL_AUTOFRESH, NORMAL_DILUTE_AUTOFRESH, SUPPLY_DILUTE_AUTOFRESH;

        private AutoFreshType() {
        }
    }

    private static final int BG_IRONSOURCE_FAILED_RECTANGLE = 1;
    private static final int BG_IRONSOURCE_FAILED_BANNER = 2;
    private boolean mIsWindowVisible = false;
    private BannerAdListener mBannerAdListener = new NullListener();
    private boolean mIsCreate;
    private boolean mIsFirstLoad = true;
    private MopubState mMopubState = new NullState();
    private boolean mIsBackground;
    private MoPubView mMoPubView;
    private BroadcastReceiver mScreenStateReceiver;
    private final Context mContext;
    private BroadcastReceiver mHomeKeyReceiver;
    private String AppMonetId;

    public CsMopubView(Context context, MoPubView moPubView, Object paramWrapper, Object sdkAdSourceRequestListener) {
        super(context);
        this.mIsCreate = true;
        this.mContext = context;
        this.mMoPubView = moPubView;
        registerScreenStateBroadcastReceiver();
        registerHomeKeyReceiver();
        moPubView.setBannerAdListener(this);
        addView(moPubView);
        this.mMopubState.onFirstAttachedToWindow();
        LogUtils.i("debug_mopub", "CsMopubView:" + this.mMoPubView.toString());
    }

    private void registerScreenStateBroadcastReceiver() {
        this.mScreenStateReceiver = new BroadcastReceiver() {
            public void onReceive(Context context, Intent intent) {
                if (intent == null) {
                    return;
                }
                String action = intent.getAction();
                if ("android.intent.action.SCREEN_OFF".equals(action)) {
                    LogUtils.i("debug_mopub", "CsMopubView window OnScreenOff");
                    CsMopubView.this.doSthOnScreenOff();
                } else if ("android.intent.action.SCREEN_ON".equals(action)) {
                    CsMopubView.this.doSthOnScreenOn();
                    LogUtils.i("debug_mopub", "CsMopubView window OnScreenOn");
                }
            }
        };
        IntentFilter filter = new IntentFilter("android.intent.action.SCREEN_OFF");
        filter.addAction("android.intent.action.USER_PRESENT");
        filter.addAction("android.intent.action.SCREEN_ON");
        this.mContext.registerReceiver(this.mScreenStateReceiver, filter);
    }

    private void unregisterScreenStateBroadcastReceiver() {
        try {
            if (this.mScreenStateReceiver != null) {
                this.mContext.unregisterReceiver(this.mScreenStateReceiver);
            }
        } catch (Exception IllegalArgumentException) {
        }
    }

    private void registerHomeKeyReceiver() {
        this.mHomeKeyReceiver = new BroadcastReceiver() {
            private static final String SYSTEM_DIALOG_REASON_KEY = "reason";
            private static final String SYSTEM_DIALOG_REASON_RECENT_APPS = "recentapps";
            private static final String SYSTEM_DIALOG_REASON_HOME_KEY = "homekey";
            private static final String SYSTEM_DIALOG_REASON_LOCK = "lock";
            private static final String SYSTEM_DIALOG_REASON_ASSIST = "assist";

            public void onReceive(Context context, Intent intent) {
                String reason = intent.getStringExtra("reason");
                if ("homekey".equals(reason)) {
                    LogUtils.i("debug_mopub", "CsMopubView ����Home��");
                    CsMopubView.this.mIsBackground = true;
                    if (CsMopubView.this.mMopubState != null) {
                        CsMopubView.this.mMopubState.onHomeKeyDown();
                    }
                } else if ("recentapps".equals(reason)) {
                    LogUtils.i("debug_mopub", "CsMopubView ����Home��");
                    if (CsMopubView.this.mMopubState != null) {
                        CsMopubView.this.mMopubState.onHomeKeyDown();
                    }
                } else if (!"lock".equals(reason)) {
                    if ("assist".equals(reason)) {
                        LogUtils.i("debug_mopub", "CsMopubView samsung����Home��");
                        if (CsMopubView.this.mMopubState != null) {
                            CsMopubView.this.mMopubState.onHomeKeyDown();
                        }
                    }
                }
            }
        };
        this.mContext.registerReceiver(this.mHomeKeyReceiver, new IntentFilter("android.intent.action.CLOSE_SYSTEM_DIALOGS"));
    }

    private void unregisterHomeKeyReceiver() {
        try {
            if (this.mHomeKeyReceiver != null) {
                this.mContext.unregisterReceiver(this.mHomeKeyReceiver);
            }
        } catch (Exception IllegalArgumentException) {
        }
    }

    protected void onWindowVisibilityChanged(int visibility) {
        super.onWindowVisibilityChanged(visibility);
        LogUtils.i("debug_mopub", "CsMopubView window visibility=" + visibility);
        this.mIsWindowVisible = (0 == visibility);
    }

    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        if (this.mIsCreate) {
            adjustBgPicAndAddView(this.mMoPubView);
            LogUtils.i("debug_mopub", "CsMopubView window onFirstAttachedToWindow");
            this.mIsCreate = false;
        } else {
            LogUtils.i("debug_mopub", "CsMopubView window onNotFirstAttachedToWindow");
            if ((this.mMopubState != null) && (!this.mIsDestroy)) {
                this.mMopubState.onAttachedToWindow();
            }
        }
    }

    void setMopubState(MopubState amsScreenOfState) {
        this.mMopubState = amsScreenOfState;
    }

    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        this.mIsCreate = false;
        LogUtils.i("debug_mopub", "CsMopubView onDetachedFromWindow");
        this.mMopubState.onDetachedFromWindow();
    }

    private void setCsAutorefreshEnabled(boolean enable) {
        setMopubViewAutoFresh(enable);
    }

    void setMopubViewAutoFresh(boolean enable) {
        if (this.mMoPubView != null) {
            LogUtils.i("adsdk_mopub", "CsMopubView setMopubViewFreshEnable:" + enable);
            this.mMoPubView.setAutorefreshEnabled(enable);
        }
    }

    private boolean isScreenOn() {
        PowerManager pm = (PowerManager) this.mContext.getSystemService("power");
        return (pm.isScreenOn());
    }

    private void doSthOnScreenOff() {
        if (!this.mIsDestroy) {
            this.mMopubState.doSthOnScreenOff();
        }
    }

    private void doSthOnScreenOn() {
        LogUtils.i("mopub_dilute", "onScreenStateChanged������");
        if (!this.mIsDestroy) {
            this.mMopubState.doSthOnScreenOn();
        }
    }

    void addMopubView(MoPubView banner) {
        this.mMoPubView = banner;
        LogUtils.d("adsdk_mopub", "����mMoPubView:" + this.mMoPubView.toString());
        this.mMoPubView.setBannerAdListener(this);

        adjustBgPicAndAddView(banner);
    }

    private void removeOldAndAddNewMopubView(MoPubView banner) {
        if ((this.mMoPubView != null) && (this.mMoPubView.hashCode() != banner.hashCode())) {
            LogUtils.d("adsdk_mopub", "hashCode����������������mMoPubView:" + this.mMoPubView.toString());
            this.mMoPubView.destroy();
        }
        addMopubView(banner);
    }

    void adjustBgPicAndAddView(MoPubView moPubView) {
        int mopubHeight = moPubView.getAdHeight();
        LogUtils.d("debug_mopub", "MoPub_Height = " + mopubHeight);
        boolean isSmallBanner = mopubHeight == 50;
        boolean isRectangleBanner = mopubHeight == 250;
        DrawUtils.resetDensity(this.mContext);
        if (isSmallBanner) {
            int width = DrawUtils.dip2px(sDpW_320);
            int height = DrawUtils.dip2px(sDpH_50);
            int bgRes = BG_IRONSOURCE_FAILED_BANNER;
            setLayoutParmaAndBgRes(moPubView, width, height, bgRes);
        } else if (isRectangleBanner) {
            int width = DrawUtils.dip2px(sDpW);
            int height = DrawUtils.dip2px(sDpH);
            int bgRes = BG_IRONSOURCE_FAILED_RECTANGLE;
            setLayoutParmaAndBgRes(moPubView, width, height, bgRes);
        }
    }

    private void setLayoutParmaAndBgRes(MoPubView moPubView, int width, int height, int bgRes) {
        ViewGroup.LayoutParams containerParams = getLayoutParams();
        if (containerParams == null) {
            containerParams = new ViewGroup.LayoutParams(1, 1);
        }
        containerParams.width = width;
        containerParams.height = height;
        setLayoutParams(containerParams);
        ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(width, height);

        setBackgroundResource(bgRes);
        removeAllViews();
        addView(moPubView, params);
    }

    public void onBannerLoaded(MoPubView banner) {
        LogUtils.d("debug_mopub", "[CsMopubView::onBannerLoaded:]" + banner.toString());
        boolean isAttached = getWindowToken() != null;
        LogUtils.i("wbq", "MoPubAutoRefresh refresh loaded isAttached=" + isAttached);
        if (doWhenCsViewDestroy(banner)) {
            return;
        }
        if ((!isAttached) && (this.mIsDestroy)) {
            LogUtils.i("adsdk_mopub", "CsMopubView::onBannerLoaded banner isNotAttached and isDestroy setAutorefreshEnabled:false");
            banner.setAutorefreshEnabled(false);
        }
        if (this.mIsBackground) {
            banner.setAutorefreshEnabled(false);
        }
        removeOldAndAddNewMopubView(banner);

        this.mIsFirstLoad = false;
        if (this.mBannerAdListener != null) {
            this.mBannerAdListener.onBannerLoaded(this);
        }
        if (!this.mIsDestroy) {
            LogUtils.d("debug_mopub", "[CsMopubView::onBannerLoaded:mMopubState:setMopubView]" + this.mMoPubView.toString());
            this.mMopubState.setMopubView(this.mMoPubView);
        }
    }

    private boolean doWhenCsViewDestroy(MoPubView banner) {
        if ((this.mIsDestroy) && (banner != null)) {
            LogUtils.i("adsdk_mopub", "CsMopubView: CsView destroy,destroy MoPubView:" + banner.toString());
            banner.setAutorefreshEnabled(false);

            return true;
        }
        return false;
    }

    public void onBannerFailed(MoPubView banner, MoPubErrorCode errorCode) {
        if (doWhenCsViewDestroy(banner)) {
            return;
        }
        removeOldAndAddNewMopubView(banner);
        if (this.mBannerAdListener != null) {
            this.mBannerAdListener.onBannerFailed(this, errorCode);
        }
        if (!this.mIsDestroy) {
            this.mMopubState.setMopubView(this.mMoPubView);
        }
    }

    public void onBannerClicked(MoPubView banner) {
        if (this.mBannerAdListener != null) {
            this.mBannerAdListener.onBannerClicked(this);
        }
    }

    public void onBannerExpanded(MoPubView banner) {
        if (this.mBannerAdListener != null) {
            this.mBannerAdListener.onBannerExpanded(this);
        }
    }

    public void onBannerCollapsed(MoPubView banner) {
        if (this.mBannerAdListener != null) {
            this.mBannerAdListener.onBannerCollapsed(this);
        }
    }

    public int getPosition() {
        return 0;
    }

    public void setAdUnitId(String adUnitId) {
        this.mMoPubView.setAdUnitId(adUnitId);
    }

    public String getAdUnitId() {
        return this.mMoPubView.getAdUnitId();
    }

    public void setKeywords(String keywords) {
        this.mMoPubView.setKeywords(keywords);
    }

    public String getKeywords() {
        return this.mMoPubView.getKeywords();
    }

    public void setLocation(Location location) {
        this.mMoPubView.setLocation(location);
    }

    public Location getLocation() {
        return this.mMoPubView.getLocation();
    }

    public int getAdHeight() {
        return this.mMoPubView.getAdHeight();
    }

    public int getAdWidth() {
        return this.mMoPubView.getAdWidth();
    }

    public Activity getActivity() {
        return this.mMoPubView.getActivity();
    }

    public void setBannerAdListener(BannerAdListener listener) {
        this.mBannerAdListener = listener;
    }

    public BannerAdListener getBannerAdListener() {
        return this.mBannerAdListener;
    }

    public void destroy() {
        doWhenCsViewDestroy(this.mMoPubView);
        this.mIsDestroy = true;
        LogUtils.i("adsdk_mopub", "CsMopubView destroy");
        unregisterScreenStateBroadcastReceiver();
        unregisterHomeKeyReceiver();
        this.mMopubState.destroy();
        this.mMopubState = new NullState();
        removeAllViews();
        setBackgroundDrawable(null);
    }

    public boolean isSmaato() {
        boolean isSmaato = false;
        LogUtils.d("adsdk_mopub", "[CsMopubView::isSmaato]����isSmaato����������" + isSmaato);
        return isSmaato;
    }

    public void setAutorefreshEnabled(boolean enabled) {
        if (enabled) {
            this.mMopubState.doSthOnScreenOn();
        } else {
            this.mMopubState.doSthOnScreenOff();
        }
    }

    public static interface BannerAdListener {
        public abstract void onBannerLoaded(CsMopubView paramCsMopubView);

        public abstract void onBannerFailed(CsMopubView paramCsMopubView, MoPubErrorCode paramMoPubErrorCode);

        public abstract void onBannerClicked(CsMopubView paramCsMopubView);

        public abstract void onBannerExpanded(CsMopubView paramCsMopubView);

        public abstract void onBannerCollapsed(CsMopubView paramCsMopubView);
    }

}
